﻿using IRQ.BaseFunctions.Drawing;
using Microsoft.WindowsMobile.Samples.Location;
using IRQ.GPS.Distance;

namespace SimpleGPSApp.Base
{
    public class DistanceCounter
    {
        private double currentDistance = 0;
        private double distanceFromStart = 0;
        private bool start = true;
        double distance = 0;
        PointF lastPosition = new PointF();

        public bool CountDistanceOn { get; set; }

        public double CurrentDistance
        {
            get { return this.currentDistance; }
        }

        public double DistanceFromStart
        {
            get { return this.distanceFromStart; }
        }

        public PointF LastPosition
        {
            get { return this.lastPosition; }
        }

        public void CountDistance(GpsPosition position)
        {
            if (start)
            {
                lastPosition.X = (float)position.Longitude;
                lastPosition.Y = (float)position.Latitude;
                start = false;
            }
            else
            {
                PointF currentPosition = new PointF((float)position.Longitude, (float)position.Latitude);
                distance = GPSCountDistance.DistanceDeg2m(
                    GPSCountDistance.CalculateDistance(lastPosition, currentPosition));

                if (distance > Root.ApplicationSettings.DistancePrecision)
                {
                    this.distanceFromStart += distance;
                    Root.Statistics.TotalDistance += distance;

                    if (CountDistanceOn)
                    {
                        this.currentDistance += distance;
                    }

                    lastPosition = currentPosition;
                }
            }
        }

        public void ResetCurrentDistance()
        {
            this.currentDistance = 0;
        }
    }
}
